package pswvclass.pswvandroid2.com.need;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.kwords.KwordAdd;
import pswvclass.pswvandroid2.com.kwords.KwordList;
import pswvclass.pswvandroid2.com.po.KWords;
import pswvclass.pswvandroid2.com.util.DBHelper;
import pswvclass.pswvandroid2.com.util.HttpUtils;

/**
 * Created by Administrator on 2018/11/6.
 */
public class Skyset extends Fragment implements View.OnClickListener {

    private String tag = "Skyset";
    private TextView plane_departsite;
    private TextView plane_termini;
    private TextView plane_starttime;
    private TextView plane_datainp;
    private TextView plane_length;
    private TextView plane_needres;
    private TextView plane_work;
    private Button dTime_click;
    private Button sTime_click;
    private Button analysis_click;
    private String need;
    private Calendar calendar;
    private Calendar calendarS;
    private Calendar calendarD;
    private Date dateS;
    private Date dateD;
    private int year;
    private int monthOfYear;
    private int dayOfMonth;
    private int hour;
    private int minute;
    private DatePickerDialog dialog;
    private TimePickerDialog tlog;
    private TextView getTime;
    protected static final int NO_ADD = 2;
    protected static final int ADD_SUCCESS = 0;
    protected static final int ERROR = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.pswv_need_skyset, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            need = bundle.getString("need");
        }
        plane_departsite = (TextView) getView().findViewById(R.id.plane_departsite);
        plane_termini = (TextView) getView().findViewById(R.id.plane_termini);
        plane_starttime = (TextView) getView().findViewById(R.id.plane_starttime);
        plane_datainp = (TextView) getView().findViewById(R.id.plane_datainp);
        plane_length = (TextView) getView().findViewById(R.id.plane_length);
        plane_needres = (TextView) getView().findViewById(R.id.plane_needres);
        plane_work = (TextView) getView().findViewById(R.id.plane_work);
        dTime_click = (Button) getView().findViewById(R.id.dTime_click);
        sTime_click = (Button) getView().findViewById(R.id.sTime_click);
        analysis_click = (Button) getView().findViewById(R.id.analysis_click);
        dTime_click.setOnClickListener(this);
        sTime_click.setOnClickListener(this);
        analysis_click.setOnClickListener(this);
    }


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ADD_SUCCESS:
                    try {
                        JSONObject data = (JSONObject) msg.obj;
                        Results rl = new Results();
                        Bundle bundle = new Bundle();
                        bundle.putInt("skysetid", data.getInt("id"));
                        rl.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, rl).commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case ERROR:
                    Toast.makeText(getContext(), "连接错误 ....", Toast.LENGTH_SHORT).show();
                    break;
                case NO_ADD:
                    Toast.makeText(getContext(), " 没有查询到....", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }

        }

        ;
    };


    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.analysis_click: {
                final String departsite = plane_departsite.getText().toString().trim();
                final String termini = plane_termini.getText().toString().trim();
                final String startTime = plane_starttime.getText().toString().trim();
                final String takeoff = plane_datainp.getText().toString().trim();
                final String length = plane_length.getText().toString().trim();
                final String needres = plane_needres.getText().toString().trim();
                final String work = plane_work.getText().toString().trim();
                if (TextUtils.isEmpty(departsite) || TextUtils.isEmpty(termini)
                        || TextUtils.isEmpty(startTime) || TextUtils.isEmpty(takeoff)
                        || TextUtils.isEmpty(length) || TextUtils.isEmpty(departsite)
                        || TextUtils.isEmpty(departsite) || TextUtils.isEmpty(needres) ||
                        TextUtils.isEmpty(work)) {
                    Toast.makeText(getContext(), "不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                DBHelper db = new DBHelper(getContext());
                SQLiteDatabase sd = db.getWritableDatabase();
                int userId = 0;
                Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                while (cursor.moveToNext()) {
                    userId = cursor.getInt(0);
                }
                cursor.close();
                final int finalUserId = userId;
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/skySetAction/addAndroidDetails";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            map1.put("userId", finalUserId + "");
                            map1.put("need", need);
                            map1.put("departsite", departsite);
                            map1.put("termini", termini);
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String dateStringD = formatter.format(dateD);
                            String dateStringS = formatter.format(dateS);
                            map1.put("startTime", dateStringS);
                            map1.put("takeoff", dateStringD);
                            map1.put("length", length);
                            map1.put("needres", needres);
                            map1.put("work", work);
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.obj = jsonObj1;
                                msg.what = ADD_SUCCESS;
                                mHandler.sendMessage(msg);
                            } else {
                                Message msg = Message.obtain();
                                msg.what = NO_ADD;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                        }
                    }
                }.start();
            }
            break;
            case R.id.sTime_click: {

                calendar = Calendar.getInstance();
                calendarS = Calendar.getInstance();
                dialog = new DatePickerDialog(getContext(),
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year1,
                                                  int monthOfYear1, int dayOfMonth1) {
                                calendarS.set(Calendar.YEAR, year1);
                                calendarS.set(Calendar.MONTH, monthOfYear1);
                                calendarS.set(Calendar.DATE, dayOfMonth1);
                            }
                        }, calendar.get(Calendar.YEAR), calendar
                        .get(Calendar.MONTH), calendar
                        .get(Calendar.DATE));
                tlog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int hour1, int minu) {
                        calendarS.set(Calendar.HOUR_OF_DAY, hour1);
                        calendarS.set(Calendar.MINUTE, minu);
                        dateS = calendarS.getTime();
                        dateD = calendarS.getTime();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String dateString = formatter.format(dateS);
                        plane_starttime.setText(dateString);
                    }
                }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
                tlog.show();
                dialog.show();
            }
            break;
            default:
                break;
        }
    }
}
